<!--
  * 性能监控组件
  *
  * @Author:    1024创新实验室-主任：卓大
  * @Date:      2024-01-01 00:00:00
  * @Wechat:    zhuda1024
  * @Email:     lab1024@163.com
  * @Copyright  1024创新实验室 （ https://1024lab.net ），Since 2012
-->
<template>
  <div class="performance-monitor">
    <a-card title="性能监控" size="small" :bordered="false">
      <template #extra>
        <a-button type="link" size="small" @click="refreshStats">
          <template #icon>
            <ReloadOutlined />
          </template>
        </a-button>
      </template>
      
      <a-row :gutter="16">
        <a-col :span="8">
          <a-statistic
            title="执行时间"
            :value="executionTime"
            :value-style="{ color: executionTimeColor }"
            suffix="ms"
          />
        </a-col>
        <a-col :span="8">
          <a-statistic
            title="内存使用"
            :value="memoryUsage"
            :value-style="{ color: memoryUsageColor }"
            suffix="MB"
          />
        </a-col>
        <a-col :span="8">
          <a-statistic
            title="数据行数"
            :value="dataRows"
            :value-style="{ color: dataRowsColor }"
          />
        </a-col>
      </a-row>
      
      <!-- 性能警告 -->
      <div v-if="warnings.length > 0" class="performance-warnings">
        <a-alert
          v-for="warning in warnings"
          :key="warning.id"
          :message="warning.message"
          :type="warning.type"
          show-icon
          closable
          @close="removeWarning(warning.id)"
          style="margin-bottom: 8px;"
        />
      </div>
      
      <!-- 性能建议 -->
      <div v-if="suggestions.length > 0" class="performance-suggestions">
        <h4>性能建议</h4>
        <a-list size="small">
          <a-list-item v-for="suggestion in suggestions" :key="suggestion.id">
            <template #actions>
              <a-tag :color="suggestion.priority === 'high' ? 'red' : suggestion.priority === 'medium' ? 'orange' : 'blue'">
                {{ suggestion.priority }}
              </a-tag>
            </template>
            <a-list-item-meta>
              <template #title>{{ suggestion.title }}</template>
              <template #description>{{ suggestion.description }}</template>
            </a-list-item-meta>
          </a-list-item>
        </a-list>
      </div>
    </a-card>
  </div>
</template>

<script setup>
  import { ref, computed, onMounted, onUnmounted } from 'vue';
  import { ReloadOutlined } from '@ant-design/icons-vue';
  import { PERFORMANCE_CONFIG, UTILS } from '../database-manager-config';

  const props = defineProps({
    executionTime: {
      type: Number,
      default: 0,
    },
    dataRows: {
      type: Number,
      default: 0,
    },
    sql: {
      type: String,
      default: '',
    },
  });

  const emit = defineEmits(['warning', 'suggestion']);

  // 性能数据
  const memoryUsage = ref(0);
  const warnings = ref([]);
  const suggestions = ref([]);
  const warningId = ref(0);

  // 计算属性
  const executionTimeColor = computed(() => {
    if (props.executionTime > PERFORMANCE_CONFIG.SLOW_QUERY_THRESHOLD) {
      return '#ff4d4f';
    } else if (props.executionTime > PERFORMANCE_CONFIG.SLOW_QUERY_THRESHOLD / 2) {
      return '#faad14';
    }
    return '#52c41a';
  });

  const memoryUsageColor = computed(() => {
    if (memoryUsage.value > PERFORMANCE_CONFIG.MEMORY_WARNING_THRESHOLD) {
      return '#ff4d4f';
    } else if (memoryUsage.value > PERFORMANCE_CONFIG.MEMORY_WARNING_THRESHOLD / 2) {
      return '#faad14';
    }
    return '#52c41a';
  });

  const dataRowsColor = computed(() => {
    if (props.dataRows > 10000) {
      return '#ff4d4f';
    } else if (props.dataRows > 5000) {
      return '#faad14';
    }
    return '#52c41a';
  });

  // 获取内存使用情况
  const getMemoryUsage = () => {
    if (performance.memory) {
      const used = performance.memory.usedJSHeapSize;
      const total = performance.memory.totalJSHeapSize;
      memoryUsage.value = Math.round(used / (1024 * 1024));
      return { used, total };
    }
    return null;
  };

  // 检查性能问题
  const checkPerformanceIssues = () => {
    const newWarnings = [];
    const newSuggestions = [];

    // 检查执行时间
    if (props.executionTime > PERFORMANCE_CONFIG.SLOW_QUERY_THRESHOLD) {
      newWarnings.push({
        id: ++warningId.value,
        message: `查询执行时间过长 (${UTILS.formatExecutionTime(props.executionTime)})`,
        type: 'warning',
      });
      
      newSuggestions.push({
        id: ++warningId.value,
        title: '优化查询性能',
        description: '建议添加索引、优化WHERE条件或减少查询范围',
        priority: 'high',
      });
    }

    // 检查内存使用
    if (memoryUsage.value > PERFORMANCE_CONFIG.MEMORY_WARNING_THRESHOLD) {
      newWarnings.push({
        id: ++warningId.value,
        message: `内存使用过高 (${memoryUsage.value}MB)`,
        type: 'error',
      });
      
      newSuggestions.push({
        id: ++warningId.value,
        title: '减少内存使用',
        description: '建议分页查询或减少返回的数据量',
        priority: 'high',
      });
    }

    // 检查数据行数
    if (props.dataRows > 10000) {
      newWarnings.push({
        id: ++warningId.value,
        message: `查询结果行数过多 (${props.dataRows}行)`,
        type: 'warning',
      });
      
      newSuggestions.push({
        id: ++warningId.value,
        title: '限制查询范围',
        description: '建议添加LIMIT子句或WHERE条件',
        priority: 'medium',
      });
    }

    // 检查SQL优化建议
    if (props.sql.toLowerCase().includes('select *')) {
      newSuggestions.push({
        id: ++warningId.value,
        title: '优化SELECT语句',
        description: '建议只选择需要的列，避免使用SELECT *',
        priority: 'low',
      });
    }

    if (props.sql.toLowerCase().includes('order by') && !props.sql.toLowerCase().includes('limit')) {
      newSuggestions.push({
        id: ++warningId.value,
        title: '添加LIMIT子句',
        description: 'ORDER BY语句建议配合LIMIT使用以提高性能',
        priority: 'medium',
      });
    }

    // 更新警告和建议
    warnings.value = newWarnings;
    suggestions.value = newSuggestions;

    // 触发事件
    if (newWarnings.length > 0) {
      emit('warning', newWarnings);
    }
    if (newSuggestions.length > 0) {
      emit('suggestion', newSuggestions);
    }
  };

  // 移除警告
  const removeWarning = (id) => {
    warnings.value = warnings.value.filter(w => w.id !== id);
  };

  // 刷新统计信息
  const refreshStats = () => {
    getMemoryUsage();
    checkPerformanceIssues();
  };

  // 监听性能数据变化
  const watchPerformance = () => {
    getMemoryUsage();
    checkPerformanceIssues();
  };

  // 定时监控
  let monitorInterval = null;

  onMounted(() => {
    if (PERFORMANCE_CONFIG.ENABLE_PERFORMANCE_MONITORING) {
      getMemoryUsage();
      checkPerformanceIssues();
      
      // 每5秒监控一次内存使用
      monitorInterval = setInterval(() => {
        getMemoryUsage();
      }, 5000);
    }
  });

  onUnmounted(() => {
    if (monitorInterval) {
      clearInterval(monitorInterval);
    }
  });

  // 暴露方法
  defineExpose({
    refreshStats,
    watchPerformance,
  });
</script>

<style scoped>
  .performance-monitor {
    margin-bottom: 16px;
  }

  .performance-warnings {
    margin-top: 16px;
  }

  .performance-suggestions {
    margin-top: 16px;
  }

  .performance-suggestions h4 {
    margin-bottom: 8px;
    color: #666;
  }
</style> 